'''
模拟 layer1 client
'''
import time
import traceback

# 导入PLCClientInterface
try:
    from abc_client import PLCClientInterface # ./
except:
    try:
        from ..layer1.abc_client import PLCClientInterface # layer2/...
    except:
        from plc_client.layer1.abc_client import PLCClientInterface #


class SimClient(PLCClientInterface): #

    def __init__(self, ip='127.0.0.1', port=1102):
        # 创建通讯客户端实例
        # self.client = modbus_tcp.TcpMaster(host=ip, port=port, timeout_in_sec=3.0)
        self.client = None
        self.ip = ip
        self.port = port


    def connect(self):
        # 连接至PLC
        try:
            # self.client.connect(self.ip, 0, 0, self.port)  # 请求大小为480B的pdu
            self.client = [0 for _ in range(500)] # sim变量值
            print(f'已连接模拟PLC {self.client}')
        except:
            print(traceback.format_exc())
        # print(f"客户端 是否连接到 plc服务端：{self.client.get_connected()}")

    def get_connected(self):
        # return self.client.get_connected()
        pass

    def read_int8(self, start=0, size=1):
        if isinstance(start, str):
            start = len(start)
        elif isinstance(start, list):
            start = start[1]
        return self.client[start]

    def read_int16(self, start=0, size=2):  # 读int16
        pass
        if isinstance(start, str):
            start = len(start)
        elif isinstance(start,list):
            start = start[1]

        return self.client[start]

    def read_bool(self, start=0, size=1): # 读bool
        pass

    def read_real(self, start=0, size=4): # 读实数
        pass

    def write_int8(self, start=0, data_int8=0): # 写int8
        if isinstance(start, str):
            start = len(start)
        elif isinstance(start, list):
            start = start[1]
        self.client[start] = data_int8

    def write_int16(self, start=0, data_int16=0): #
        if isinstance(start, str):
            start = len(start)
        elif isinstance(start, list):
            start = start[1]

        self.client[start] = data_int16

    def write_real(self, start=0, data_real=1.0): # 写实数  用于发送坐标等
        pass

    def write_bool(self, start=0, data_bool=False): # 写bool
        pass

    def read_string(self, start=0, size=50, dbnumber=0): # 读 string  size=256
        pass

    def write_string(self, start=0, data_str='hello', dbnumber=0): # write string
        pass

    def close(self):
        self.client= None
        # print(f"plc 连接状态：{self.client.get_connected()}")


def test_SimClient():
    ly1_client = SimClient()
    ly1_client.connect()
    ly1_client.write_int8(start=10, data_int8=100)
    value = ly1_client.read_int8(start=10)
    print(value)
    ly1_client.close()

if __name__ == "__main__":
    test_SimClient()